package com.njupt.Tree;

import java.util.ArrayList;
import java.util.List;



/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/6 18:56
 * @Description: 530. 二叉搜索树的最小绝对差
 * @Version: 1.0
 */


public class GetMinimumDifference {
    private Integer minGap = Integer.MAX_VALUE;

   private TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {

        calMinNum(root);
        return this.minGap;

    }

    private void calMinNum(TreeNode root) {
        if(root == null){
            return;
        }
        calMinNum(root.left);  //左
        if(this.pre != null){  //中
            this.minGap = Math.min(this.minGap,root.val - this.pre.val);
        }
        this.pre = root;   //记录前一个节点
        calMinNum(root.right);  //右
    }


    public int getMinimumDifference1(TreeNode root) {

        List<Integer> results = new ArrayList<>();

        traverse(root,results);
        if(results.size() < 2) return  0;
        int min = Integer.MAX_VALUE;

        for (int i = 0; i < results.size()-1; i++) {
            if(results.get(i+1) - results.get(i) <min){
                min = results.get(i+1) - results.get(i);
            }
        }
        return min;

    }

    private void traverse(TreeNode root, List<Integer> results) {
        if(root == null){
            return;
        }
        traverse(root.left,results);
        results.add(root.val);
        traverse(root.right,results);
    }

    public static void main(String[] args) {
//        TreeNode root = new TreeNode(4);
//        root.left = new TreeNode(2);
//        root.right = new TreeNode(6);
//        root.left.left = new TreeNode(1);
//        root.left.right = new TreeNode(3);

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(0);
        root.right = new TreeNode(48);
        root.right.left = new TreeNode(12);
        root.right.right = new TreeNode(49);

        GetMinimumDifference test = new GetMinimumDifference();
        int minimumDifference = test.getMinimumDifference1(root);
        System.out.println(minimumDifference);
    }
}
